import { createRouter, createWebHistory } from 'vue-router'

const Home = () => import('@/views/Home.vue')
const Category = () => import('@/views/Category.vue')
const Product = () => import('@/views/Product.vue')
const Cart = () => import('@/views/Cart.vue')
const Checkout = () => import('@/views/Checkout.vue')
const User = () => import('@/views/User.vue')
const Search = () => import('@/views/Search.vue')
const Login = () => import('@/views/Login.vue')
const CategoryDebug = () => import('@/components/CategoryDebug.vue')
const Orders = () => import('@/views/Orders.vue')
const OrderDetail = () => import('@/views/OrderDetail.vue')

const router = createRouter({
  history: createWebHistory(),
  routes: [
    { path: '/', name: 'home', component: Home, meta: { requiresAuth: true } },
    { path: '/category/:id?', name: 'category', component: Category, meta: { requiresAuth: false } },
    { path: '/product/:id', name: 'product', component: Product, meta: { requiresAuth: true } },
    { path: '/cart', name: 'cart', component: Cart, meta: { requiresAuth: true } },
    { path: '/checkout', name: 'checkout', component: Checkout, meta: { requiresAuth: true } },
    { path: '/user', name: 'user', component: User, meta: { requiresAuth: true } },
    { path: '/search', name: 'search', component: Search, meta: { requiresAuth: true } },
    { path: '/login', name: 'login', component: Login },
    { path: '/category-debug', name: 'category-debug', component: CategoryDebug, meta: { requiresAuth: false } },
    { path: '/orders', name: 'orders', component: Orders, meta: { requiresAuth: true } },
    { path: '/order/detail/:id', name: 'orderDetail', component: OrderDetail, meta: { requiresAuth: true } },
    { path: '/:pathMatch(.*)*', redirect: '/' },
  ],
  scrollBehavior() {
    return { top: 0 }
  },
})

// 全局路由守卫：需要鉴权的路由校验 token
router.beforeEach(async (to) => {
  if (!to.meta?.requiresAuth) return true
  try {
    // 优先检查localStorage中是否存在token，解决刷新页面时的时序问题
    if (typeof window !== 'undefined' && window.localStorage) {
      const token = localStorage.getItem('token')
      
      // 如果localStorage中没有token，直接重定向到登录页
      if (!token) {
        console.warn('localStorage中未找到token，重定向到登录页')
        return { name: 'login', query: { redirect: to.fullPath } }
      }
    }
    
    // 延迟验证，确保token有足够时间从localStorage加载
    await new Promise(resolve => setTimeout(resolve, 50))
    
    const { useUserStore } = await import('@/stores/user')
    const store = useUserStore()
    
    // 1. 检查是否有token
    if (!store.token) {
      console.log('未检测到token，重定向到登录页面')
      return { name: 'login', query: { redirect: to.fullPath } }
    }
    
    // 2. 调用后端验证token是否有效
    // 任何后端请求都会携带token，后端会以此判断登录状态
    // 我们通过getCurrentUserId来验证token的有效性
    const { getCurrentUserId } = await import('@/services/auth')
    await getCurrentUserId()
    
    // 3. token验证通过，允许访问
    return true
  } catch (error) {
    console.error('Token验证失败:', error.message)
    
    // 检查是否是订单页面刷新导致的403错误
    if (to.path.includes('/orders') && error.response && error.response.status === 403) {
      console.warn('订单页面刷新时token验证失败，尝试重新加载页面')
      // 对于订单页面的403错误，我们可以尝试等待token完全加载后再继续
      await new Promise(resolve => setTimeout(resolve, 100))
      
      // 再次检查localStorage中的token
      if (typeof window !== 'undefined' && window.localStorage) {
        const token = localStorage.getItem('token')
        if (token) {
          // 如果token存在但验证失败，可能是token过期，清除后重定向到登录页
          console.warn('token存在但验证失败，清除token后重定向到登录页')
          try {
            const { useUserStore } = await import('@/stores/user')
            const store = useUserStore()
            store.logout()
          } catch (e) {
            console.error('清除用户状态失败:', e)
            localStorage.removeItem('token')
          }
        }
      }
    } else {
      // 其他情况下，清除token并重定向到登录页
      try {
        const { useUserStore } = await import('@/stores/user')
        const store = useUserStore()
        store.logout()
      } catch (e) {
        console.error('清除token失败:', e)
      }
    }
    
    return { name: 'login', query: { redirect: to.fullPath } }
  }
})

export default router


